/**
 * @form 表单js
 * @author yuebin
 */

/* ------------------- example ------------------------
<form id="form-step-last" name="formStepLast" novalidate autocomplete="off" action="javascript:;"><div class="form-group">
    <div class="form-item">
        <label class="form-label">贷款用途：</label>
        <div class="form-content">
            <div class="select" style="z-index:49;">
                <i class="icon icon-arrow-down"></i>
                <input type="hidden" name="daikuanyt" class="select-value" required />
                <div class="select-text placeholder">请选择贷款用途</div>
                <ul class="option-list">
                    <li data-value="0">买房</li>
                </ul>
            </div>
            <p class="error-info"></p>
        </div>
    </div>
    <div class="form-item">
        <label class="form-label">手机号码：</label>
        <div class="form-content">
            <input type="text" class="input" required id="phone" name="phone" maxlength="11" value="" placeholder="请输入手机号码" />
            <p class="error-info"></p>
        </div>
    </div>
    <div class="form-item">
        <label class="form-label">验证码：</label>
        <div class="form-content">
            <input type="text" class="input input-120 float-l" name="captcha" maxlength="6" placeholder="请输入验证码"/>
            <a href="javascript:;" class="btn btn-white btn-get-code" id="get-captcha">获取验证码</a>
            <p class="error-info" id="captcha-error-info"></p>
        </div>
    </div>
    <div class="form-item">
        <label class="form-label"><a href="javascript:;" class="prev-step">上一步</a>&nbsp;&nbsp;</label>
        <div class="form-content">
            <button class="btn btn-info btn-submit" type="submit">提交</button>
            <p class="form-tips"></p>
            <p class="form-error-info"></p>
        </div>
    </div>
</div></form>

$form.data('verifier', {        //验证器定义
    name: function(value) {
        return '错误提示';
    }
}).on('doSubmit', function(e) {      //通过验证器验证后触发自定义提交事件
    // TODO
});
*/


define('tool/form', function(require, exports, module) {
    'use strict';
    
    var $select = null;
    var $selectText = null;
    var $selectValue = null;
    var $optilnList = null;

    // 模拟下拉菜单点击事件
    $(document).on('click', '.select', function(e) {
        var _$select = $(this).closest('.select');

        if (_$select.children('.option-list:visible').length) {
            return true;
        }

        $optilnList && $optilnList.off().hide();
        $select && $select.removeClass('select-focus');
        $select = _$select;
        $optilnList = $select.children('.option-list');
        $selectText = $select.children('.select-text');
        $selectValue = $select.children('.select-value');

        // 增加focus状态，移除错误状态和提示
        $select.addClass('select-focus').removeClass('error').nextAll('.error-info').hide();
        
        // 重置选择状态
        var _selectText = $.trim($selectText.text());
        $optilnList.children().removeClass('selected').each(function(i, v) {
            if ($.trim($(this).text()) === _selectText) {
                $(this).addClass('selected');
                return false;
            }
        });

        // 待选项事件绑定
        $optilnList.show().on('mouseenter', 'li', function(e) {
            if (!$(this).hasClass('selected')) {
                $(this).addClass('selected').siblings('.selected').removeClass('selected');
            }
        }).on('click', 'li', function(e) {
            $selectValue.val($(this).data('value') || $(this).text());
            $selectText.text($(this).text()).removeClass('placeholder');
            $select.removeClass('select-focus');
        });

        // 若刚展开，阻止事件冒泡
        return false;
    });
    
    // 模拟radio button点击事件
    $(document).on('click', '.radio-user', function(e) {
        if (!$(e.target).hasClass('radio-user-checked')) {
            $(e.target).addClass('radio-user-checked')
                .find('input:radio').prop('checked', true)
                .end().siblings('.radio-user-checked').removeClass('radio-user-checked')
                .find('input:radio').prop('checked', false);
        }
    });

    // 聚焦时清楚错误状态和提示
    $(document).on('focus', '.input', function(e) {
        $(e.target).removeClass('error').nextAll('.error-info').hide();
    });

    // 点击任何位置关闭选项列表
    $(document).on('click', function() {
        $optilnList && $optilnList.hide();
        $select && $select.removeClass('select-focus');
    });

    // 通用验证写法
    $(document).on('submit', function(e) {
        var verifier = $(e.target).data('verifier');
        var invalidate = false;
        var postData = $(e.target).serializeArray();

        $(e.target).find('.error').removeClass('error').end().find('.error-info, .form-error-info').hide();

        for (var i = 0; i < postData.length; i++) {
            var $target = $(e.target).find('input[name=' + postData[i].name + ']');
            
            if ($target.attr('required') && !postData[i].value) {
                var _requireTips = $target.attr('placeholder');

                if ($target.hasClass('select-value')) {
                    $target = $target.closest('.select');
                    _requireTips = $target.find('.select-text').text();
                }

                // 目标元素增加error样式，并填写和展示错误提示
                $target.addClass('error').nextAll('.error-info').show().text(_requireTips);
                    
                invalidate = true;
            } else if (typeof verifier === 'object' && verifier[postData[i].name]) {
                var verifyTips = verifier[postData[i].name](postData[i].value);
                if (verifyTips) {
                    // 若为模拟select元素则目标元素为.select
                    if ($target.hasClass('select-value')) {
                        $target = $target.closest('.select');
                    }

                    // 目标元素增加error样式，并填写和展示错误提示
                    $target.addClass('error').nextAll('.error-info').show().text(verifyTips);
                        
                    invalidate = true;
                }
            }
        }

        // 验证未通过，阻止默认事件
        if (invalidate) {
            e.preventDefault();
        } else {
            // 触发自定义事件
            $(e.target).trigger('doSubmit');
        }

        // 若未定义action属性，则阻止form表单的提交
        if(!$(e.target).attr('action')) {
            e.preventDefault();
        }
    });

    // addon 文字点击hover
    $(document).on('click', '.form-group .addon', function(e) {
        $(e.target).prevAll('.select').trigger('click');
        setCaretPosition($(e.target).prevAll('.input')[0], $(e.target).prevAll('.input').length+1);
    });

    //获取光标位置函数
    function getCursortPosition(ctrl) { 
        var CaretPos = 0;
        // IE Support
        if (document.selection) { 
            ctrl.focus();
            var Sel = document.selection.createRange();
            Sel.moveStart('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        } else if (ctrl.selectionStart || ctrl.selectionStart == '0') {    // Firefox support
            CaretPos = ctrl.selectionStart; return (CaretPos); 
        }
    };

    //设置光标位置函数 
    function setCaretPosition(ctrl, pos){
        if (ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select(); 
        } 
    };
});